/**
 * 页面：创作中心
 * 功能：数字人创作工作台，包含模型管理、AI配置、语音配置、内容创作等功能
 */
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Card, Tabs, Input, Button, Select, Upload, Slider, Switch, message, Space, Tag } from 'antd'
import { UploadOutlined, PlayCircleOutlined, SaveOutlined, SettingOutlined, UserOutlined, SoundOutlined, RobotOutlined } from '@ant-design/icons'
import './Worker.css'

const { TabPane } = Tabs
const { TextArea } = Input
const { Option } = Select

interface Project {
  id: string
  name: string
  model: string
  createdAt: string
  status: 'draft' | 'published'
}

function Index() {
  const navigate = useNavigate()
  const [activeTab, setActiveTab] = useState('model')
  
  // 模型配置
  const [modelUrl, setModelUrl] = useState('/模型_卖萌.glb')
  const [modelScale, setModelScale] = useState(0.7)
  const [modelPosition, setModelPosition] = useState({ x: 0, y: 0, z: 0 })
  
  // AI配置
  const [apiKey, setApiKey] = useState(localStorage.getItem('moonshot_api_key') || '')
  const [aiModel, setAiModel] = useState('moonshot-v1-8k')
  const [temperature, setTemperature] = useState(0.7)
  const [maxTokens, setMaxTokens] = useState(1000)
  const [streamEnabled, setStreamEnabled] = useState(true)
  
  // 语音配置
  const [asrEnabled, setAsrEnabled] = useState(true)
  const [ttsVoice, setTtsVoice] = useState('x5_lingxiaoxuan_flow')
  const [ttsSpeed, setTtsSpeed] = useState(1.0)
  const [ttsPitch, setTtsPitch] = useState(1.0)
  
  // 内容配置
  const [systemPrompt, setSystemPrompt] = useState('你是数字展馆的讲解助手，请用简洁中文回答。')
  const [welcomeMessage, setWelcomeMessage] = useState('欢迎来到数字展馆，我是您的AI助手。')
  
  // 项目列表
  const [projects] = useState<Project[]>([
    { id: '1', name: '数字展馆讲解员', model: '/模型_卖萌.glb', createdAt: '2024-01-15', status: 'published' },
    { id: '2', name: 'AI客服助手', model: '/模型_卖萌.glb', createdAt: '2024-01-10', status: 'draft' },
  ])

  const handleSaveConfig = () => {
    const config = {
      model: { url: modelUrl, scale: modelScale, position: modelPosition },
      ai: { apiKey, model: aiModel, temperature, maxTokens, streamEnabled },
      voice: { asrEnabled, ttsVoice, ttsSpeed, ttsPitch },
      content: { systemPrompt, welcomeMessage }
    }
    localStorage.setItem('worker_config', JSON.stringify(config))
    if (apiKey) {
      localStorage.setItem('moonshot_api_key', apiKey)
    }
    message.success('配置已保存')
  }

  const handlePreview = () => {
    handleSaveConfig()
    navigate('/num')
  }

  const handleUploadModel = (file: File) => {
    // 这里应该上传到服务器，暂时使用本地URL
    const url = URL.createObjectURL(file)
    setModelUrl(url)
    message.success('模型上传成功')
    return false // 阻止默认上传
  }

  return (
    <div className="worker-container">
      <div className="worker-header">
        <div className="header-content">
          <h1 className="worker-title">创作中心</h1>
          <p className="worker-subtitle">配置您的数字人，创建个性化AI交互体验</p>
        </div>
        <Space>
          <Button icon={<SaveOutlined />} onClick={handleSaveConfig}>
            保存配置
          </Button>
          <Button type="primary" icon={<PlayCircleOutlined />} onClick={handlePreview}>
            预览效果
          </Button>
        </Space>
      </div>

      <div className="worker-content">
        <Tabs activeKey={activeTab} onChange={setActiveTab} className="worker-tabs">
          {/* 数字人模型 */}
          <TabPane 
            tab={<span><UserOutlined />数字人模型</span>} 
            key="model"
          >
            <Card title="3D模型配置" className="config-card">
              <div className="config-item">
                <label>模型文件</label>
                <div className="upload-section">
                  <Input 
                    value={modelUrl} 
                    onChange={(e) => setModelUrl(e.target.value)}
                    placeholder="输入模型URL或上传文件"
                  />
                  <Upload
                    beforeUpload={handleUploadModel}
                    showUploadList={false}
                    accept=".glb,.gltf"
                  >
                    <Button icon={<UploadOutlined />}>上传模型</Button>
                  </Upload>
                </div>
                <div className="help-text">支持 GLB/GLTF 格式，推荐使用 GLB</div>
              </div>

              <div className="config-item">
                <label>模型缩放</label>
                <Slider
                  min={0.1}
                  max={2}
                  step={0.1}
                  value={modelScale}
                  onChange={setModelScale}
                />
                <div className="slider-value">{modelScale.toFixed(1)}</div>
              </div>

              <div className="config-item">
                <label>模型位置</label>
                <Space>
                  <Input 
                    type="number" 
                    placeholder="X" 
                    value={modelPosition.x}
                    onChange={(e) => setModelPosition({...modelPosition, x: parseFloat(e.target.value) || 0})}
                    style={{ width: 100 }}
                  />
                  <Input 
                    type="number" 
                    placeholder="Y" 
                    value={modelPosition.y}
                    onChange={(e) => setModelPosition({...modelPosition, y: parseFloat(e.target.value) || 0})}
                    style={{ width: 100 }}
                  />
                  <Input 
                    type="number" 
                    placeholder="Z" 
                    value={modelPosition.z}
                    onChange={(e) => setModelPosition({...modelPosition, z: parseFloat(e.target.value) || 0})}
                    style={{ width: 100 }}
                  />
                </Space>
              </div>
            </Card>
          </TabPane>

          {/* AI配置 */}
          <TabPane 
            tab={<span><RobotOutlined />AI配置</span>} 
            key="ai"
          >
            <Card title="大模型配置" className="config-card">
              <div className="config-item">
                <label>API Key</label>
                <Input.Password
                  value={apiKey}
                  onChange={(e) => setApiKey(e.target.value)}
                  placeholder="请输入 Moonshot API Key"
                />
                <div className="help-text">API Key 仅保存在本地浏览器，不会上传到服务器</div>
              </div>

              <div className="config-item">
                <label>模型选择</label>
                <Select value={aiModel} onChange={setAiModel} style={{ width: '100%' }}>
                  <Option value="moonshot-v1-8k">Moonshot v1-8k</Option>
                  <Option value="moonshot-v1-32k">Moonshot v1-32k</Option>
                  <Option value="moonshot-v1-128k">Moonshot v1-128k</Option>
                </Select>
              </div>

              <div className="config-item">
                <label>Temperature（创意度）</label>
                <Slider
                  min={0}
                  max={2}
                  step={0.1}
                  value={temperature}
                  onChange={setTemperature}
                />
                <div className="slider-value">{temperature.toFixed(1)}</div>
                <div className="help-text">值越高，回复越随机；值越低，回复越确定</div>
              </div>

              <div className="config-item">
                <label>最大Token数</label>
                <Input 
                  type="number" 
                  value={maxTokens}
                  onChange={(e) => setMaxTokens(parseInt(e.target.value) || 1000)}
                  min={100}
                  max={8000}
                />
              </div>

              <div className="config-item">
                <label>
                  <Switch checked={streamEnabled} onChange={setStreamEnabled} />
                  <span style={{ marginLeft: 8 }}>启用流式传输</span>
                </label>
                <div className="help-text">开启后，AI回复将以打字机效果逐字显示</div>
              </div>
            </Card>
          </TabPane>

          {/* 语音配置 */}
          <TabPane 
            tab={<span><SoundOutlined />语音配置</span>} 
            key="voice"
          >
            <Card title="语音识别（ASR）" className="config-card">
              <div className="config-item">
                <label>
                  <Switch checked={asrEnabled} onChange={setAsrEnabled} />
                  <span style={{ marginLeft: 8 }}>启用语音识别</span>
                </label>
                <div className="help-text">开启后，用户可以通过语音输入与数字人交互</div>
              </div>
            </Card>

            <Card title="语音合成（TTS）" className="config-card" style={{ marginTop: 24 }}>
              <div className="config-item">
                <label>发音人</label>
                <Select value={ttsVoice} onChange={setTtsVoice} style={{ width: '100%' }}>
                  <Option value="x5_lingxiaoxuan_flow">晓璇（温柔女声）</Option>
                  <Option value="x5_lingfeiyi_flow">飞易（专业男声）</Option>
                  <Option value="x5_catherine_flow">Catherine（英文女声）</Option>
                </Select>
              </div>

              <div className="config-item">
                <label>语速</label>
                <Slider
                  min={0.5}
                  max={2}
                  step={0.1}
                  value={ttsSpeed}
                  onChange={setTtsSpeed}
                />
                <div className="slider-value">{ttsSpeed.toFixed(1)}x</div>
              </div>

              <div className="config-item">
                <label>音调</label>
                <Slider
                  min={0.5}
                  max={2}
                  step={0.1}
                  value={ttsPitch}
                  onChange={setTtsPitch}
                />
                <div className="slider-value">{ttsPitch.toFixed(1)}x</div>
              </div>
            </Card>
          </TabPane>

          {/* 内容配置 */}
          <TabPane 
            tab={<span><SettingOutlined />内容配置</span>} 
            key="content"
          >
            <Card title="对话配置" className="config-card">
              <div className="config-item">
                <label>系统提示词</label>
                <TextArea
                  rows={4}
                  value={systemPrompt}
                  onChange={(e) => setSystemPrompt(e.target.value)}
                  placeholder="定义数字人的角色和对话风格"
                />
                <div className="help-text">用于设定数字人的身份、性格和回答风格</div>
              </div>

              <div className="config-item">
                <label>欢迎语</label>
                <Input
                  value={welcomeMessage}
                  onChange={(e) => setWelcomeMessage(e.target.value)}
                  placeholder="数字人首次交互时的欢迎语"
                />
              </div>
            </Card>
          </TabPane>

          {/* 我的作品 */}
          <TabPane 
            tab={<span>我的作品</span>} 
            key="projects"
          >
            <Card title="作品列表" className="config-card">
              <div className="projects-grid">
                {projects.map((project) => (
                  <Card 
                    key={project.id} 
                    hoverable
                    className="project-card"
                    actions={[
                      <Button type="link" onClick={() => navigate('/num')}>预览</Button>,
                      <Button type="link">编辑</Button>,
                      <Button type="link" danger>删除</Button>
                    ]}
                  >
                    <div className="project-header">
                      <h3>{project.name}</h3>
                      <Tag color={project.status === 'published' ? 'green' : 'orange'}>
                        {project.status === 'published' ? '已发布' : '草稿'}
                      </Tag>
                    </div>
                    <div className="project-info">
                      <div>模型: {project.model}</div>
                      <div>创建时间: {project.createdAt}</div>
                    </div>
                  </Card>
                ))}
              </div>
              <Button type="dashed" block style={{ marginTop: 16 }}>
                创建新作品
              </Button>
            </Card>
          </TabPane>
        </Tabs>
      </div>
    </div>
  )
}

export default Index
